package com.study.spring.tcp;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicLong;

/**
 * TCP服务器端
 *
 * @author zhang
 * @version 1.0
 * @date 2019/04/03
 */
public class MsgServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(MsgServer.class);

    private final AtomicLong longA = new AtomicLong(10L);

    public static void main(String[] args) {
        MsgServer msgServer = new MsgServer();
        msgServer.setUpServer(9090);
    }

    public void setUpServer(int port) {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            LOGGER.info("服务器启动监听!");
            while (true) {
                Socket socket = serverSocket.accept();
                LOGGER.info(socket.getRemoteSocketAddress().toString());
                handler(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    /**
     * @param socket
     */
    private void handler(Socket socket) {
        InputStream inputStream;
        OutputStream outputStream;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            while (true) {
                if (longA.addAndGet(1) % 2 == 0) {
                    throw new RuntimeException("test");
                }
                byte flag = dataInputStream.readByte();
                LOGGER.info("接受的消息类型是: {}", flag);
                int totalLen = dataInputStream.readInt();
                LOGGER.info("接受的消息体长度是：{}", totalLen);

                byte[] data = new byte[totalLen - 5];
                dataInputStream.readFully(data);
                String msg = new String(data, StandardCharsets.UTF_8);
                LOGGER.info("发来的消息是 : {}", msg);
                dataOutputStream.writeUTF("收到" + msg);
                dataOutputStream.flush();

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
